package com.ccteam.fluidmusic.ui

import android.Manifest
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.ccteam.fluidmusic.NavSplashDirections
import com.ccteam.fluidmusic.databinding.FragmentPermissionBinding
import com.ccteam.fluidmusic.utils.PermissionHandler

/**
 * @author Xiaoc
 * @since 2021/1/7
 *
 * 权限申请界面Fragment
 */
class PermissionFragment : Fragment() {

    private var _binding: FragmentPermissionBinding? = null
    private val binding get() = _binding!!

    private lateinit var permissionHandler: PermissionHandler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        permissionHandler = PermissionHandler(
            requireContext().applicationContext,
            requireActivity().activityResultRegistry,{
                !shouldShowRequestPermissionRationale(it)
            },{
                findNavController().navigate(NavSplashDirections.actionGlobalMainActivity())
                requireActivity().finish()
            })
        lifecycle.addObserver(permissionHandler)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentPermissionBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.btnPermissionRequest.setOnClickListener {
            permissionHandler.permissionRequest(arrayOf(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ))
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}